package com.wwj.app.v1;

import com.wwj.core.common.Constants;
import com.wwj.core.pay.weixin.HttpClientUtil;
import com.wwj.core.wawa.entity.Player;
import com.wwj.core.wawa.service.IPlayerService;
import com.wwj.framework.controller.BaseController;
import com.wwj.framework.utils.ReturnData;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

/**
 * Created by Administrator on 2017/11/3.
 */
@Controller
@RequestMapping("/v1/auth")
public class AuthController extends BaseController {

    @Resource
    private JedisPool jedisPool;

    @Resource
    private IPlayerService playerService;

    @RequestMapping("/login")
    @ResponseBody
    public ReturnData login(@RequestParam String origin_type, @RequestParam String openid, @RequestParam String nickname,
                            @RequestParam String sex, @RequestParam String province, @RequestParam String city,
                            @RequestParam String country, @RequestParam String headimgurl, @RequestParam String unionid,
                            @RequestParam String access_token, @RequestParam(required = false) String os, HttpServletRequest request) {
        try {
            //先验证微信用户是否存在
//            String url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + access_token + "&openid=" + openid +"&lang=zh_CN";
//            if("android".equalsIgnoreCase(os)) {
//                url = "https://api.weixin.qq.com/sns/userinfo?access_token="  + access_token + "&openid=" + openid +"&lang=zh_CN";
//            }
            //因为IOS审核的时候，手机没有安装微信，所以不需要去验证了
            if(!"ios".equalsIgnoreCase(os)) {
                String url = "https://api.weixin.qq.com/sns/userinfo?access_token="  + access_token + "&openid=" + openid +"&lang=zh_CN";
                String response = HttpClientUtil.doGet(url);
                if(response == null || response.isEmpty()) {
                    return new ReturnData().failure("验证微信用户失败，请联系客服!");
                }
                JSONObject object = JSONObject.fromObject(response);
                if(object.containsKey("errcode")) {
                    logger.error("微信验证失败：" + response);
                    return new ReturnData().failure("验证微信用户失败!");
                }
                if(!object.getString("openid").equals(openid)) {
                    return new ReturnData().failure("非法微信用户!");
                }
            }

            Player player = new Player();
            player.setOriginType(origin_type);
            player.setOpenId(openid);
            player.setNickname(nickname);
            player.setSex(sex);
            player.setProvince(province);
            player.setCity(city);
            player.setCountry(country);
            player.setHeaderIcon(headimgurl);
            player.setUnionId(unionid);
            player = playerService.dealLogin(player);
            if(player.getStatus() == 0) {
                return new ReturnData().failure("当前用户处于禁用状态，请联系客服");
            }

            //保存session
            JSONObject json = new JSONObject();
            String sessionId = request.getSession().getId();
            json.put("sessionId", sessionId);
            json.put("userId", player.getId());
            json.put("userName", player.getNickname());
            Jedis jedis = jedisPool.getResource();
            jedis.setex(sessionId, Constants.SESSION_TIME_OUT, json.toString());
            jedis.close();

            return new ReturnData().success(player);
        } catch (Exception e) {
            logger.error("", e);
            return new ReturnData().success("登录失败，请联系客服!");
        }
    }

    @RequestMapping("/logout")
    @ResponseBody
    public ReturnData logout(@RequestParam int playerId, @RequestParam String jsessionid, HttpServletRequest request) {
        try {
            Jedis jedis = jedisPool.getResource();
            jedis.del(jsessionid);
            jedis.close();
            return new ReturnData().success();
        } catch (Exception e) {
            logger.error("", e);
            return new ReturnData().success("系统错误，请联系客服!");
        }
    }
}
